<template>
  <div>
    <basic-container-one>
      <vue-element-loading :active="isActive" spinner="bar-fade-scale" color="#409eff" background-color="rgba(255,255,255,0.2)"/>
      <el-form :inline="true" :model="formInline" >
        <div style="margin-top: 22px">
          <!--<el-form-item>
            <el-input clearable v-model="formInline.gameName" placeholder="游戏名称"/>
          </el-form-item>-->
          <el-form-item>
            <el-select v-model="formInline.gameName" filterable clearable placeholder="游戏名称">
              <el-option
                v-for="item in gamelist"
                :key="item.gameName"
                :label="item.gameName"
                :value="item.gameName"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="queryData.querDate"
              clearable
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="queryFunc">查询</el-button>
            <el-button type="primary" icon="el-icon-download" @click="downloadReportFunc">下载</el-button>
          </el-form-item>
        </div>
      </el-form>
    </basic-container-one>
    <basic-container>
      <div style="margin-top: 10px">

        <el-radio-group v-model="tabPositionThird" @change="handleClickThird">
          <el-radio-button label="userRoleAccount">充值总人数 | 总充值金额 | 总平台币金额</el-radio-button>
          <el-radio-button label="newRoleUserValueWithIMEICount">首充人数 | 首充金额 | 首充平台币金额</el-radio-button>
          <el-radio-button label="tradeUserCount">续充人数 | 续充金额 | 续充平台币金额</el-radio-button>
        </el-radio-group>
      </div>
      <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
      <div id="main" style="margin-top: 20px; height:300px;width: 100%;background-color: #394056;"></div>

      <div style="margin-top: 20px">
        <el-table
          :data="dailyStatisticsList"
          show-summary
          stripe
          :summary-method="dailyStatisticsListSum"
          ref="el-table"
          style="width: 100%">
          <el-table-column
            prop="data"
            label="日期" key="0">
            <template slot-scope="scope">
              <span class="skucost-pruice">{{ scope.row.day | formatDate('YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payNumberAvg" label="人均付费" key="1">
            <template slot-scope="scope">
              <span  v-if="scope.row.payNumberAvg == 'NaN'" >0</span>
              <span  v-if="scope.row.payNumberAvg > 0"
                class="skucost-pruice">{{ (scope.row.payNumberAvg / 100).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payNumberTotal" label="充值总人数" key="2">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.payNumberTotal }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payAmountTotal" label="充值总金额" key="3">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.payAmountTotal / 100 }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="platformCurrencyTotal" key="4"
                           label="总平台币金额">
            <template slot-scope="scope">
              <span class="skucost-pruice">{{ scope.row.platformCurrencyTotal }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="firstPayNumberTotal" label="首充人数" key="5">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.firstPayNumberTotal }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="firstPayAmountTotal" label="首充收款" key="6" >
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.firstPayAmountTotal / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="firstPlatformCurrencyTotal" label="首充平台币金额" key="7">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.firstPlatformCurrencyTotal }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="rechargePayNumberTotal"  label="续充人数"
                           key="8">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.rechargePayNumberTotal}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="rechargePayAmountTotal" label="续充收款"
                           key="9">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.rechargePayAmountTotal / 100 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="rechargePlatformCurrencyTotal" key="10" label="续充平台币金额">
            <template slot-scope="scope">
              <span
                class="skucost-pruice">{{ scope.row.rechargePlatformCurrencyTotal}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="block" style="margin-top: 20px;">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>

    </basic-container>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import * as echarts from 'echarts/core';
import {
  GridComponent
} from 'echarts/components';
import {
  LineChart
} from 'echarts/charts';
import {
  SVGRenderer
} from 'echarts/renderers';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legendScroll';

import {queryDailyStatisticsQr} from '@/api/statistics/statistics'
import {queryGamesQr} from "@/api/system/details";
import moment from "moment";
import {cloneObj, parseParam} from '@/util/util'
import {getToken} from "@/util/auth";
import VueElementLoading from 'vue-element-loading'

echarts.use(
  [GridComponent, LineChart, SVGRenderer]
);

export default {
  name: "day",
  data() {
    return {
      isActive: false,
      gamelist:[],
      formInline: {
        gameName: '',
        startDate: 0,
        endDate: 0
      },
      page: {
        current: 1,
        size: 10,
        total: 0,
      },
      time: null,
      queryData: {
        querDate: [new Date(new Date(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 6)).setHours(0, 0, 0, 0)),
          new Date(new Date().setHours(23, 59, 59, 0))],
      },
      dailyStatisticsList: [],
      date: '',
      checked: false,
      tabPositionThird: 'userRoleAccount',
      isshowtrue: false,
      ischange: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

    }

  },
  components: {
    VueElementLoading
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  mounted() {
    this.loadGames()
    this.initChart()
    this.queryDailyStatisticsFunc()
  },


  methods: {
    loadGames() {
      queryGamesQr().then(res => {
        this.gamelist = res.data.data
      })
    },
    /**
     * 下载报表
     */
    downloadReportFunc() {

      let formData = cloneObj(this.formInline);
      formData.startDate = moment(this.queryData.querDate[0]).startOf('day').valueOf()
      formData.endDate = moment(this.queryData.querDate[1]).endOf('day').valueOf()
      window.location.href = `/api/blade-statistic/statistics/queryDailyStatisticsReportQr?${parseParam(formData)}&blade-auth=${getToken()}`
    },

    /**
     * 搜索按钮
     */
    queryFunc() {
      this.refreshTable()
    },

    dailyStatisticsListSum(param) {

      const {columns, data} = param;

      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => item[column.property]);
        if (values.length != 0) {
          sums[index] = values.reduce((prev, curr) => {
            return prev + curr;
          })
        }
        if (column.property === "payAmountTotal" || column.property === "firstPayAmountTotal" || column.property === "rechargePayAmountTotal") {
          sums[index] = sums[index] / 100
        }
        sums[1] = (sums[3] / sums[2]).toFixed(2);
        if(sums[1] == 'NaN'){
          sums[1] = 0
        }
      });

      return sums;
    },

    refreshTable() {
      this.isActive = true
      this.queryDailyStatisticsFunc()
    },

    queryDailyStatisticsFunc() {
      let formData = cloneObj(this.formInline);
      formData.startDate = moment(this.queryData.querDate[0]).startOf('day').valueOf()
      formData.endDate = moment(this.queryData.querDate[1]).endOf('day').valueOf()
      queryDailyStatisticsQr(formData, this.page.current, this.page.size).then(res => {
        this.isActive = false
        let data = res.data.data
        this.dailyStatisticsList = data.records
        this.page.total = data.total
        this.handleClickThird(this.tabPositionThird)
      })
    },
    handleSizeChange(val) {
      this.page.size = val
      this.refreshTable()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.refreshTable()
    },
    handleClickThird(tab) {

      let xdata = this.dailyStatisticsList.map(d => moment(d.day).format('YYYY-MM-DD'))
      let ydata = []
      switch (tab) {
        case 'userRoleAccount':
          ydata.push(this.dailyStatisticsList.map(d => d.payNumberTotal))
          ydata.push(this.dailyStatisticsList.map(d => d.payAmountTotal/100))
          ydata.push(this.dailyStatisticsList.map(d => d.platformCurrencyTotal))
          this.setChartsData("充值总人数", "总充值金额", "总平台币金额", xdata, ydata)
          break;
        case 'newRoleUserValueWithIMEICount':
          ydata.push(this.dailyStatisticsList.map(d => d.firstPayNumberTotal))
          ydata.push(this.dailyStatisticsList.map(d => d.firstPayAmountTotal/100))
          ydata.push(this.dailyStatisticsList.map(d => d.firstPlatformCurrencyTotal))
          this.setChartsData("首充人数","首充收款", "首充平台币金额", xdata, ydata)
          break;
        case 'tradeUserCount':
          ydata.push(this.dailyStatisticsList.map(d => d.rechargePayNumberTotal))
          ydata.push(this.dailyStatisticsList.map(d => d.rechargePayAmountTotal/100))
          ydata.push(this.dailyStatisticsList.map(d => d.rechargePlatformCurrencyTotal))
          this.setChartsData("续充人数","续充收款", "续充平台币金额", xdata, ydata)
          break;
      }
    },

    initChart() {
      this.charts = echarts.init(document.getElementById('main'));
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        this.charts.resize();
      });
    },

    setChartsData(name1, name2, name3, xdata, ydata) {

      this.charts.clear()

      const option = {
        tooltip: {
          trigger: 'axis',
          confine: true, //将 tooltip 框限制在图表的区域内，在移动端开发时非常有用
          // extraCssText: 'background:rgba(0,0,0);border:0;color:rgba(225,225,225);',

        },
        title: {
          text: "每日概况",
          textStyle: { //主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
            fontSize: 18,
            color: '#ffffff',
            fontStyle: 'normal',
            fontWeight: 'normal',
          },
          x: '3%', //水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
          y: '3%', //垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        legend: {
          orient: 'horizontal',
          x: '80%', //水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
          y: '3%', //垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
          textStyle: { //主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
            fontSize: 15,
            color: '#ffffff',
            fontStyle: 'normal',
            fontWeight: 'normal',
          },
          data: [name1, name2, name3]
        },
        grid: { //调整图表上下左右位置
          top: '20%',
          left: '3%',
          right: '3%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xdata,
          boundaryGap: false // 不留白，从原点开始
        },
        yAxis: {
          type: 'value',
          axisPointer: {
            type: 'cross',
            label: {
              // backgroundColor: '#6a7985'
            }
          }
        },
        series: [
          {
            name: name1,
            data: ydata[0],
            type: 'line',
            symbol: "none",

            lineStyle: {
              width: 1//设置线条粗细
            },
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(58,77,233,0.3)'
              }, {
                offset: 1,
                color: 'rgba(58,77,233,0.1)'
              }])
            },
          },
          {
            name: name2,
            data: ydata[1],
            type: 'line',
            symbol: "none",
            lineStyle: {
              width: 1//设置线条粗细
            },
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(137,189,27,0.3)'
              }, {
                offset: 1,
                color: 'rgba(137,189,27,0.1)'
              }])
            },
          },
          {
            name: name3,
            data: ydata[2],
            type: 'line',
            symbol: "none",
            lineStyle: {
              width: 1//设置线条粗细
            },
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(38,64,181,0.3)'
              }, {
                offset: 1,
                color: 'rgba(38,64,181,0.1)'
              }])
            },
          }]
      };

      this.charts.setOption(option);

    }
  }
}
</script>

